package com.fit4as.util.reflect
{
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;
import flash.utils.describeType;

public class ClassUtil
{

    public static function getClass( instance : Object ) : Class
    {
        return getClassByName( getQualifiedClassName( instance ));
    }
    
    public static function getClassByName( name : String ) : Class
    {
		return Class( getDefinitionByName( name ));    	
    }

    public static function getField( target : Class, name : String ) : Field
    {
        var result : Field = new Field( target, name );
        return result;
    }
    
    public static function getFieldType( target : Class, name : String ) : Class
    {
		var description : XML = describeType( target );
	    var fieldDescriptions : XMLList = description..variable;
	    var fieldDescription : * = fieldDescriptions.(@name == name);
	    if( fieldDescription.length() == 0 ) fieldDescription = description..accessor.(@name == name);
	
		return getClassByName( fieldDescription.@type );
	    	
    }

    public static function getMethod( target : Class, name : String, parameterTypes : Array = null) : Method
    {
        var result : Method = new Method( target, name, parameterTypes );
        return result;
    }
    
    public static function getMethodReturnType( target : Class, name : String ) : Class
    {
    	 var description : XML = describeType( target );
    	 
        return getClassByName( description..method.(@name == name).@returnType );
    }

	public static function getMethodParameterTypes( target : Class, name : String ) : Array
	{
		var result : Array = new Array();
        var descriptions : XMLList = describeType( target )..method.(@name == name).parameter;
        if( descriptions == null || descriptions.length() == 0 ) return result;
        
        for( var i : int = 0; i < descriptions.length(); i++ )
        {
            var type : String = descriptions[ i ].@type;
            if( type == "*" ) type = "Object";
            result.push( getClassByName( type ));
        }
        return result;
	}

}
}